<template>
  <div class="home">
    <SearchHeader></SearchHeader>
    <TabHeader :classifyList="classifyList"  @changeTab="changeTab" ref="tabHeader"></TabHeader>
    <div class="cont">
      <div class="channel" v-for="(channel,index) in booklist" :key="index">
        <div class="ch-title" v-if="channel.books.length > 0" >
          <span>{{ channel.classifyName }}</span>
          <span class="ch-more" v-if="activeTabIndex === 0" @click="changeTabIndex({id:channel.classifyId,name:channel.classifyName})">查看更多</span>
        </div>
        <!-- 每3个一行 -->
        <div class="ch-book" v-if="channel.books.length > 0">
          <div class="row">
            <van-grid :column-num="3" :border="false">
              <van-grid-item v-for="(book,index) in channel.books" :key="'b'+index">
                <div class="item" @click="goBookDetail(book)">
                  <div class="cover">
                    <img :src="book.cover" alt="book.name" srcset="">
                  </div>
                  <div class="name">{{book.name}}</div>
                  <div class="author">{{book.author}}</div>
                </div>
              </van-grid-item>
            </van-grid>
          </div>
        </div>
      </div>
    </div>
    <Footer v-if="!loading"></Footer>
  </div>
</template>

<script>
import TabHeader from '~/components/TabHeader.vue'
import SearchHeader from '~/components/SearchHeader'
import Footer from '~/components/Footer'
console.log('process.env.NODE_ENV2:',process.env.NODE_ENV)
export default {
  async asyncData(ctx) {
    try{
      // 获取首页全部数据
      const homeData = await ctx.$axios.get('/api/getHomeData')
      const classifyList = homeData.classifyList || []
      const booklist = homeData.booklist
      return {
        classifyList,
        booklist,
      }
    }catch (err){
      ctx.$errorHandler(err)
    }
  },
  name: 'Home',
  components:{
    TabHeader,
    SearchHeader,
    Footer
  },
  data(){
    return {
      classifyList:[],
      booklist:[],
      loading:true,
      activeTabIndex: Number(this.$route.query.activeTabIndex) || 0
      // classifyActiveIndex:0 // 默认显示tab的索引
    }
  },
  head() {
    return {
      meta:[
        {
          hid:'keywords',
          name:'keywords',
          content:this.classifyList.map(item=>(item.name+'小说,免费在线')).join(',')
        }
      ]
    } 
  },
  mounted() {
    // 获取历史浏览记录
    let categoryPageData = this.commonData.getPageHistory(this.commonData.categoryPageHistoryKey)
    if(categoryPageData){
      this.$dialog.confirm({
        title:'提示',
        message:`上次浏览至<<${decodeURIComponent(categoryPageData.bookName)}-${decodeURIComponent(categoryPageData.categoryName)}>>,是否跳转到哪里？`
      }).then(()=>{
        console.log('confirm');
        this.$router.push(decodeURIComponent(categoryPageData.path))
      }).catch(()=>{
        console.log('catch');
        this.commonData.clearPageHistory(this.commonData.categoryPageHistoryKey)
      })
    }
    this.loading = false
  },
  methods: {
    goBookDetail(book){
      // 友盟统计
      uMengTj('首页','浏览',book.name)
      this.$router.push({path : '/book', query:{bookId: book.id}})
    },
    async init(){
      const homeData = await this.$axios.get('/api/getHomeData')
      this.classifyList = homeData.classifyList
      this.booklist = homeData.booklist
    },
    async changeTab(classify,index){
      console.log('changeTab:',classify);
      if(classify){
        this.activeTabIndex = index
        this.$router.push({ query: { activeTabIndex: index } })
        // 友盟统计
        uMengTj('首页','切换tab',classify.title)
        // 全部
        if(classify.id === 0){
          this.init()
        }else{
          // 查询已完结，上架中的书籍
          let res = await this.$axios.get('/api/getBookByClassify?classifyId='+classify.id+'&isShow=1&status=1')
          this.booklist = [
            {
              classifyId: classify.id,
              classifyName: classify.name,
              books:res.books
            }
          ]
        }
      }
      
      
    },
    changeTabIndex(channel){
      let index = this.classifyList.findIndex(item=>{return +item.id === +channel.id}) + 1
      // 因为多了全部，所以index要加1
      this.activeTabIndex = index
      this.$router.push({ query: { activeTabIndex: index } })
      // 修改tab组件高亮的tab页
    }
  },
}
</script>

<style lang="scss" scoped>
.home{
  .cont{
    .channel{
      width: 350px;
      margin: auto;
      .ch-title{
        height:  40px;
        line-height: 40px;
        font-size: 18px;
        color:rgba(0,0,0,0.85);
        text-align: left;
        margin-top: 10px;
        
        &::before{
          content:'';
          width: 0px;
          height: 18px;
          border-right: 5px solid black;
          margin-right: 5px;
        }
        .ch-more{
          float: right;
          font-size: 14px;
          text-decoration: underline;
        }

      }
      .ch-book{
        width: 100%;
        .row{
          width: 100%;
          display: flex;
          align-items: center;
          margin-bottom: 20px;
          .item{
            width: 100%;
            // height: 130px;
            margin-bottom: 10px;
            text-align: left;
            &:last-child{
              margin-left: 0px;
            }
            .cover{
              width: 100%;
              height: 130px;
              text-align: center;
              img{
                width: 100%;
                height: 100%;
              }
            }
            .name{
              font-size: 14px;
            }
            .author{
              font-size: 14px;
              color:#aba59a;
            }
          }
        }
      }
    }
  }
}
</style>

